﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace DomainInfoLib
{
    public class ExcuterQueue :IExcuter
    {
        Queue<QueryItem> QueueC;

        public void ExcAll(List<QueryItem> Clist)
        {
            QueueC = new Queue<QueryItem>(Clist);

            Start(ThreadCount);
        }

        List<Thread> tPool = new List<Thread>();

        private void Start(int Count)
        {
            tPool = new List<Thread>();

            for (int i = 1; i <= Count; i++)
            {
                Thread t = new Thread(new ThreadStart(DoWork));
                t.IsBackground = true;
                tPool.Add(t);
                t.Start();
            }
        }

        private void DoWork()
        {
            QueryItem item;

            bool IsContinnue = true ;

            while (IsContinnue)
            {
                item = PeekAUnDoneItemFromQueue();
                if (item == null)
                {
                    IsContinnue = false;
                    break;
                }
                item.Done += new GottenRegisteInfoHandle(item_Done);
                item.GetRegisteInfo();
            }
        }

        private QueryItem PeekAUnDoneItemFromQueue()
        {
            lock (QueueC)
            {
                if (QueueC.Count <= 0)
                {
                    return null;
                }
                return QueueC.Dequeue();
            }
        }

        void item_Done(QueryItem item)
        {
            AnItemDone(item);
        }


        public event DoneHandle AnItemDone;


        public void Stop()
        {
            foreach (Thread t in tPool)
            {
                t.Abort();
            }
        }

        public int ThreadCount { get; set; }


        public void SetThreadCount(int threadCount)
        {
            this.ThreadCount = threadCount;
        }
    }
}
